# Echo client program
import socket
import sys
import thread
import time

HOST = '192.168.1.3'    # The remote host
PORT = 2008             # The same port as used by the server
s = None
for res in socket.getaddrinfo(HOST, PORT, socket.AF_UNSPEC, socket.SOCK_STREAM):
    af, socktype, proto, canonname, sa = res
    try:
        s = socket.socket(af, socktype, proto)
    except socket.error, msg:
        s = None
        continue
    try:
        s.connect(sa)
        s.send(socket.gethostname())
    except socket.error, msg:
        s.close()
        s = None
        continue
    break
if s is None:
    print 'could not open socket'
    sys.exit(1)

def loop():
   while 1:
      	received=s.recv(1024)  
	if not received: break
	print received

### VARIABILI
execflag=0 #Verifica che il thread sia eseguito una sola volta

try:  
    while 1:
    	if execflag==0:
    	    thread.start_new_thread(loop,())
    	    time.sleep(1)
 	    execflag=1 
        #data = s.recv(1024)
        data = raw_input("\nInput: ")
        s.send(data)
	if data=="BYE":
	    s.close()
	    sys.exit(0)      
	#if not received: break
        #print 'Received', repr(received)	    
except KeyboardInterrupt:       
    s.send(socket.gethostname()+": closing connection")
    s.close()
    sys.exit(0)
